package com.mygame.components

import com.almasb.fxgl.entity.Entity
import com.almasb.fxgl.entity.component.Component
import com.almasb.fxgl.pathfinding.astar.AStarMoveComponent
import com.mygame.Const
import kotlin.jvm.optionals.getOrNull

class PathAIComponent : Component() {
    private lateinit var astarMove: AStarMoveComponent
    private var pathList: List<Entity>? = null
    private var nextPathIndex = 0
    override fun onAdded() {
        astarMove = entity.getComponent(AStarMoveComponent::class.java)
        pathList = entity.properties.getValueOptional<List<Entity>>(Const.PATH).getOrNull()
    }

    override fun onUpdate(tpf: Double) {
        if (!entity.isActive) return
        pathList?.get(nextPathIndex)?.let {
            // 将entity旋转到向量的方向
            entity.rotateToVector(it.center.subtract(entity.center))
            //if (!astarMove.isAtDestination) return//开放这个注释,是必须要到达指上一个追踪点之后,才会进行下一步追踪
            val cellX: Int = (it.center.x / Const.CELL_WIDTH).toInt()
            val cellY: Int = (it.center.y / Const.CELL_HEIGHT).toInt()
            val tagCell = try {
                astarMove.grid.get(cellX, cellY)
            } catch (e: ArrayIndexOutOfBoundsException) {//避免越界
                return
            }
            val currentCell = astarMove.currentCell.get()
            val distance = currentCell.distance(tagCell)//当前和追踪目标的格子距离,按1格2格算
            if (distance > 0) {//不是path路径点的格子都需要移动
                astarMove.moveToCell(tagCell)
            } else {//到了path路径点的格子就往下一个path移动
                nextPathIndex++
                if (nextPathIndex >= pathList!!.size) {
                    entity.removeFromWorld()
                }
                println("thisPath:${it.properties.getString(Const.NAME)}  nextPathIndex=$nextPathIndex ")
            }
        }
    }
}